import java.io.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class LibraryManager {
    private final List<Book> books = new ArrayList<>();
    private final List<Reader> readers = new ArrayList<>();
    private final List<BorrowRecord> borrowRecords = new ArrayList<>();
    private final int BORROW_LIMIT = 5;
    private final String RECORD_FILE_PATH = "borrow_records.txt";

    public LibraryManager() {
        loadBorrowRecordsFromFile();
    }

    public void borrowBook(String isbn, String cardId) throws BookAlreadyBorrowedException, BorrowLimitExceededException {
        Book book = books.stream().filter(b -> b.getIsbn().equals(isbn)).findFirst()
                .orElseThrow(() -> new RuntimeException("未找到ISBN为" + isbn + "的图书"));
        Reader reader = readers.stream().filter(r -> r.getCardId().equals(cardId)).findFirst()
                .orElseThrow(() -> new RuntimeException("未找到借书证号为" + cardId + "的读者"));

        if (book.isBorrowed()) {
            throw new BookAlreadyBorrowedException("图书《" + book.getTitle() + "》（ISBN：" + isbn + "）已借出，无法重复借阅");
        }

        if (reader.getBorrowedCount() >= BORROW_LIMIT) {
            throw new BorrowLimitExceededException("读者" + reader.getName() + "（借书证号：" + cardId + "）当前借阅数已达上限（" + BORROW_LIMIT + "本），无法继续借阅");
        }

        book.setBorrowed(true);
        reader.incrementBorrowedCount();
        BorrowRecord record = new BorrowRecord(book, reader, LocalDateTime.now());
        borrowRecords.add(record);
        saveBorrowRecordToFile(record);
        System.out.println("借阅成功！" + record);
    }

    public void returnBook(String isbn, String cardId) {
        BorrowRecord record = borrowRecords.stream()
                .filter(r -> r.getBook().getIsbn().equals(isbn)
                        && r.getReader().getCardId().equals(cardId)
                        && r.getReturnTime() == null)
                .findFirst()
                .orElseThrow(() -> new RuntimeException("未找到读者" + cardId + "借阅图书" + isbn + "的未还记录"));

        Book book = record.getBook();
        Reader reader = record.getReader();
        book.setBorrowed(false);
        reader.decrementBorrowedCount();
        record.setReturnTime(LocalDateTime.now());

        updateBorrowRecordInFile();
        System.out.println("归还成功！" + record);
    }

    public List<BorrowRecord> getRecordsByReader(String cardId) {
        return borrowRecords.stream()
                .filter(r -> r.getReader().getCardId().equals(cardId))
                .collect(Collectors.toList());
    }

    public void addBook(Book book) {
        books.add(book);
    }

    public void addReader(Reader reader) {
        readers.add(reader);
    }

    private void loadBorrowRecordsFromFile() {
        File file = new File(RECORD_FILE_PATH);
        if (!file.exists()) return;

        try (BufferedReader br = new BufferedReader(new FileReader(file))) {
            String line;
            while ((line = br.readLine()) != null) {
                String[] parts = line.split(",");
                if (parts.length != 4) continue;

                Book book = books.stream().filter(b -> b.getIsbn().equals(parts[0])).findFirst().orElse(null);
                Reader reader = readers.stream().filter(r -> r.getCardId().equals(parts[1])).findFirst().orElse(null);
                if (book == null || reader == null) continue;

                LocalDateTime borrowTime = LocalDateTime.parse(parts[2], BorrowRecord.FORMATTER);
                LocalDateTime returnTime = "null".equals(parts[3]) ? null : LocalDateTime.parse(parts[3], BorrowRecord.FORMATTER);

                BorrowRecord record = new BorrowRecord(book, reader, borrowTime);
                if (returnTime != null) {
                    record.setReturnTime(returnTime);
                } else {
                    book.setBorrowed(true);
                    reader.incrementBorrowedCount();
                }
                borrowRecords.add(record);
            }
        } catch (IOException e) {
            System.err.println("加载借阅记录失败：" + e.getMessage());
        }
    }

    private void saveBorrowRecordToFile(BorrowRecord record) {
        try (BufferedWriter bw = new BufferedWriter(new FileWriter(RECORD_FILE_PATH, true))) {
            bw.write(record.toFileString());
            bw.newLine();
        } catch (IOException e) {
            System.err.println("保存借阅记录失败：" + e.getMessage());
        }
    }

    private void updateBorrowRecordInFile() {
        try (BufferedWriter bw = new BufferedWriter(new FileWriter(RECORD_FILE_PATH))) {
            for (BorrowRecord record : borrowRecords) {
                bw.write(record.toFileString());
                bw.newLine();
            }
        } catch (IOException e) {
            System.err.println("更新借阅记录失败：" + e.getMessage());
        }
    }
}